<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>敏感性分析与参数优化</title>
    <link href="{{ url_for('static',filename='bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
    <link href="{{ url_for('static',filename='bootstrap/bootstrap-icons-1.11.1/bootstrap-icons.min.css') }}" rel="stylesheet">
    <script src="{{ url_for('static',filename='jquery/jquery-3.7.1.min.js') }}"></script>
    <script src="{{ url_for('static',filename='bootstrap/js/bootstrap.bundle.min.js') }}"></script>
    <style>
        :root {
            --primary-color: #2E7D32;
            --secondary-color: #81C784;
            --accent-color: #DCEDC8;
            --text-color: #212121;
            --light-text: #757575;
            --light-green: #E8F5E9;
            --dark-green: #1B5E20;
            --amber: #FFD54F;
            --brown: #795548;
            --leaf-green: #66BB6A;
        }

        body {
            background-color: #F8F9FA;
            background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M54.627 0l.83.828-1.415 1.415L51.8 0h2.827zM5.373 0l-.83.828L5.96 2.243 8.2 0H5.374zM48.97 0l3.657 3.657-1.414 1.414L46.143 0h2.828zM11.03 0L7.372 3.657 8.787 5.07 13.857 0H11.03zm32.284 0L49.8 6.485 48.384 7.9l-7.9-7.9h2.83zM16.686 0L10.2 6.485 11.616 7.9l7.9-7.9h-2.83zm20.97 0l9.315 9.314-1.414 1.414L34.828 0h2.83zM22.344 0L13.03 9.314l1.414 1.414L25.172 0h-2.83zM32 0l12.142 12.142-1.414 1.414L30 .828 17.272 13.556l-1.414-1.414L28 0h4zM.284 0l28 28-1.414 1.414L0 2.544V0h.284zM0 5.373l25.456 25.455-1.414 1.415L0 8.2V5.374zm0 5.656l22.627 22.627-1.414 1.414L0 13.86v-2.83zm0 5.656l19.8 19.8-1.415 1.413L0 19.514v-2.83zm0 5.657l16.97 16.97-1.414 1.415L0 25.172v-2.83zM0 28l14.142 14.142-1.414 1.414L0 30.828V28zm0 5.657L11.314 44.97 9.9 46.386l-9.9-9.9v-2.828zm0 5.657L8.485 47.8 7.07 49.212 0 42.143v-2.83zm0 5.657l5.657 5.657-1.414 1.415L0 47.8v-2.83zm0 5.657l2.828 2.83-1.414 1.413L0 53.456v-2.83zM54.627 60L30 35.373 5.373 60H8.2L30 38.2 51.8 60h2.827zm-5.656 0L30 41.03 11.03 60h2.828L30 43.858 46.142 60h2.83zm-5.656 0L30 46.686 16.686 60h2.83L30 49.515 40.485 60h2.83zm-5.657 0L30 52.343 22.344 60h2.83L30 55.172 34.828 60h2.83zM32 60l-2-2-2 2h4zM59.716 0l-28 28 1.414 1.414L60 2.544V0h-.284zM60 5.373L34.544 30.828l1.414 1.415L60 8.2V5.374zm0 5.656L37.373 33.656l1.414 1.414L60 13.86v-2.83zm0 5.656l-19.8 19.8 1.415 1.413L60 19.514v-2.83zm0 5.657l-16.97 16.97 1.414 1.415L60 25.172v-2.83zM60 28L45.858 42.142l1.414 1.414L60 30.828V28zm0 5.657L48.686 44.97l1.415 1.415 9.9-9.9v-2.828zm0 5.657L51.515 47.8l1.414 1.414L60 42.143v-2.83zm0 5.657l-5.657 5.657 1.414 1.415L60 47.8v-2.83zm0 5.657l-2.828 2.83 1.414 1.413L60 53.456v-2.83zM39.9 16.385l1.414-1.414L30 3.658 18.686 14.97l1.415 1.415 9.9-9.9 9.9 9.9zm-2.83 2.828l1.415-1.414L30 9.313 21.515 17.8l1.414 1.413L30 11.8l7.07 7.414v-.002zm-2.827 2.83l1.414-1.416L30 14.97l-5.657 5.657 1.414 1.415L30 17.8l4.243 4.242zm-2.83 2.827l1.415-1.414L30 20.626l-2.828 2.83 1.414 1.414L30 23.456l1.414 1.414zM56.87 59.414L58.284 58 30 29.716 1.716 58l1.414 1.414L30 32.544l26.87 26.87z' fill='%2381c784' fill-opacity='0.07' fill-rule='evenodd'/%3E%3C/svg%3E");
            color: var(--text-color);
            padding: 2rem;
            min-height: 100vh;
        }

        /* 页面标题部分 */
        .page-header {
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 1.2rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.07);
        }

        .page-title {
            color: var(--primary-color);
            font-weight: 700;
            font-size: 2rem;
            margin-bottom: 0;
            position: relative;
            padding-left: 2.2rem;
        }

        .page-title::before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 1.8rem;
            height: 1.8rem;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%232E7D32' d='M12 2C13.1 2 14 2.9 14 4C14 5.1 13.1 6 12 6C10.9 6 10 5.1 10 4C10 2.9 10.9 2 12 2M21 9V7L15 1H5C3.89 1 3 1.89 3 3V21C3 22.11 3.89 23 5 23H19C20.11 23 21 22.11 21 21V9M19 9H14V4H5V21H19V9Z'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-size: contain;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
        }

        .btn-back {
            background-color: white;
            border-color: rgba(0, 0, 0, 0.1);
            color: var(--light-text);
            padding: 0.6rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-back:hover {
            background-color: rgba(0, 0, 0, 0.05);
            color: var(--text-color);
            border-color: rgba(0, 0, 0, 0.2);
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            padding: 0.6rem 1.2rem;
            border-radius: 8px;
            font-weight: 500;
            box-shadow: 0 2px 8px rgba(46, 125, 50, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
            box-shadow: 0 4px 12px rgba(46, 125, 50, 0.4);
            transform: translateY(-2px);
        }

        /* 标签页导航 */
        .tab-navigation {
            display: flex;
            margin-bottom: 2rem;
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        .tab-btn {
            flex: 1;
            padding: 1rem;
            text-align: center;
            background: none;
            border: none;
            font-weight: 500;
            color: var(--light-text);
            transition: all 0.3s ease;
            position: relative;
            cursor: pointer;
        }

        .tab-btn i {
            margin-right: 0.5rem;
        }

        .tab-btn.active {
            color: var(--primary-color);
            background-color: var(--accent-color);
        }

        .tab-btn.active::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 3px;
            background-color: var(--primary-color);
        }

        /* 标签页内容 */
        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* 参数部分 */
        .parameter-section {
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            margin-bottom: 2rem;
            position: relative;
        }

        .parameter-section::before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 6px;
            background: linear-gradient(90deg, var(--leaf-green), var(--secondary-color));
        }

        .parameter-header {
            padding: 1.5rem;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            padding-bottom: 0;
        }

        .parameter-title {
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0;
            font-size: 1.25rem;
            display: flex;
            align-items: center;
        }

        .parameter-title i {
            margin-right: 0.5rem;
            color: var(--leaf-green);
            font-size: 1.35rem;
        }

        .parameter-subtitle {
            color: var(--light-text);
            font-size: 0.9rem;
            margin-top: 0.5rem;
        }

        .parameter-content {
            padding: 1.5rem;
        }

        /* 表单样式 */
        .form-label {
            font-weight: 500;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }

        .form-control, .form-select {
            padding: 0.5rem 0.75rem;
            border-radius: 8px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 3px rgba(129, 199, 132, 0.25);
        }

        /* 特殊样式 */
        .bound-input {
            background-color: #f5f5f5 !important;
            color: var(--light-text);
        }

        .current-input {
            background-color: white !important;
        }

        /* 参数输入行样式 */
        .input-group-custom {
            background-color: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

        .input-group-custom:hover {
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* 表格样式 */
        .results-table {
            margin-bottom: 0;
        }

        .results-table th {
            background-color: var(--light-green);
            color: var(--dark-green);
            font-weight: 600;
            white-space: nowrap;
        }

        .new-value-header, .change-percent-header {
            background-color: #5cb85c !important;
            color: white !important;
        }

        .table-success th {
            background-color: var(--light-green) !important;
            color: var(--dark-green) !important;
        }

        .table-info th {
            background-color: #d1ecf1 !important;
            color: #0c5460 !important;
        }

        /* 结果变化样式 */
        .positive-change {
            color: #28a745;
            font-weight: bold;
        }

        .negative-change {
            color: #dc3545;
            font-weight: bold;
        }

        .no-change {
            color: #6c757d;
        }

        /* 结果容器 */
        .results-container {
            max-height: 500px;
            overflow-y: auto;
            overflow-x: auto;
            border: 1px solid #dee2e6;
            border-radius: 8px;
        }

        /* 卡片样式增强 */
        .card {
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            border: none;
        }

        .card-header {
            border-radius: 12px 12px 0 0 !important;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }

        .card-title {
            display: flex;
            align-items: center;
        }

        .card-title i {
            margin-right: 0.5rem;
        }

        /* 进度条容器 */
        .progress {
            height: 1rem;
            border-radius: 0.5rem;
        }

        .progress-bar {
            background-color: var(--secondary-color);
        }

        /* 按钮样式增强 */
        .btn-success {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-success:hover {
            background-color: var(--leaf-green);
            border-color: var(--leaf-green);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(129, 199, 132, 0.4);
        }

        .btn-outline-primary {
            color: var(--primary-color);
            border-color: var(--primary-color);
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-outline-primary:hover {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            transform: translateY(-2px);
        }

        .btn-outline-danger {
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-outline-danger:hover {
            transform: translateY(-2px);
        }

        /* 返回顶部按钮 */
        .back-to-top {
            position: fixed;
            bottom: 2rem;
            right: 2rem;
            width: 3rem;
            height: 3rem;
            border-radius: 50%;
            background-color: var(--primary-color);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.3s ease;
            z-index: 1000;
        }

        .back-to-top.visible {
            opacity: 1;
        }

        .back-to-top:hover {
            background-color: var(--dark-green);
            transform: translateY(-3px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        }

        /* 浮动提示 */
        .floating-alert {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            min-width: 300px;
            text-align: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }

        /* 优化输入框样式 */
        .actual-input {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
            text-align: center;
        }

        .actual-input:focus {
            border-color: var(--secondary-color);
            outline: none;
            box-shadow: 0 0 0 2px rgba(129, 199, 132, 0.25);
        }

        /* 优化复选框样式 */
        .optimize-checkbox {
            margin-top: 0.25rem;
            transform: scale(1.2);
        }

        /* 响应式样式 */
        @media (max-width: 768px) {
            .page-title {
                font-size: 1.6rem;
            }

            .header-actions {
                flex-direction: column;
                gap: 0.5rem;
            }

            .tab-btn {
                padding: 0.75rem 0.5rem;
                font-size: 0.9rem;
            }

            .tab-btn i {
                margin-right: 0.3rem;
            }

            body {
                padding: 1rem;
            }

            .parameter-content {
                padding: 1rem;
            }

            .results-container {
                max-height: 300px;
            }

            .input-group-custom .row > div {
                margin-bottom: 0.5rem;
            }
        }

        /* 为防止内容突然跳动，添加占位样式 */
        .tab-navigation-placeholder {
            display: none;
            height: 56px;
        }

        /* 为非中文字符设置等宽字体 */
        body, input, select, textarea, button, .form-control, .form-select {
            font-family: "PingFang SC", "Microsoft YaHei", "Noto Sans SC", "Source Han Sans SC", "WenQuanYi Micro Hei", -apple-system, system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        /* 专门针对数字和英文字符的等宽字体设置 */
        .form-control, .form-select, table td, table th, pre, code, .actual-input {
            font-family: "SF Mono", "JetBrains Mono", "Cascadia Code", Menlo, Consolas, monospace, "PingFang SC", "Microsoft YaHei", "Noto Sans SC";
        }

        /* 敏感性分析结果容器 - 不限制高度 */
        .sensitivity-results-container {
            overflow-x: auto;
            border: 1px solid #dee2e6;
            border-radius: 8px;
        }

        /* 敏感性分析表格优化 */
        .sensitivity-table-container {
            position: relative;
            overflow-x: auto; /* 只保留横向滚动 */
            overflow-y: visible; /* 纵向不滚动，显示所有内容 */
            border: 1px solid #dee2e6;
            border-radius: 8px;
            background-color: white;
        }

        /* 表格基础样式 */
        .sensitivity-table {
            position: relative;
            width: max-content; /* 确保表格可以横向滚动 */
            min-width: 100%;
        }

        /* 固定表头 */
        .sensitivity-table thead th {
            z-index: 30;
            background-color: var(--light-green) !important;
            border-bottom: 2px solid #dee2e6;
        }

        /* 固定第一列 */
        .sensitivity-table th:first-child,
        .sensitivity-table td:first-child {
            position: sticky;
            left: 0;
            z-index: 25;
            background-color: white !important;
            border-right: 2px solid #dee2e6;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            min-width: 150px;
            max-width: 200px;
        }

        /* 固定表头的第一列（左上角） */
        .sensitivity-table thead th:first-child {
            z-index: 35; /* 最高优先级 */
            background-color: var(--light-green) !important;
        }

        /* 单元格内容布局 */
        .mu-cell {
            padding: 8px !important;
            text-align: center;
            vertical-align: middle;
            min-width: 120px;
            background-color: white;
            border: 1px solid #dee2e6;
        }

        .mu-content {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .mu-value {
            font-weight: 600;
            font-size: 0.9em;
            color: var(--primary-color);
            margin: 0;
        }

        .optimize-checkbox {
            transform: scale(1.2);
            margin: 0;
        }

        /* 行高亮效果 - 不影响固定列 */
        .sensitivity-table tbody tr:hover td:not(:first-child) {
            background-color: rgba(129, 199, 132, 0.1) !important;
        }

        /* 列高亮效果 - 不影响固定列 */
        .sensitivity-table td.column-hover:not(:first-child) {
            background-color: rgba(129, 199, 132, 0.15) !important;
        }

        /* μ值颜色编码 */
        .mu-high { color: #dc3545; font-weight: bold; }
        .mu-medium { color: #fd7e14; font-weight: 600; }
        .mu-low { color: #28a745; }

        /* 响应式优化 */
        @media (max-width: 768px) {
            .mu-cell {
                min-width: 80px;
                padding: 6px !important;
            }

            .mu-value {
                font-size: 0.8em;
            }

            .optimize-checkbox {
                transform: scale(1.1);
            }
        }

        /* 实际结果输入表格样式优化 */
        .actual-results-table {
            position: relative;
            overflow-x: auto;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            background-color: white;
        }

        .actual-results-table table {
            min-width: 100%;
            width: max-content;
        }

        /* 固定第一列并设置合适宽度 */
        .actual-results-table th:first-child,
        .actual-results-table td:first-child {
            position: sticky;
            left: 0;
            z-index: 10;
            background-color: white !important;
            border-right: 2px solid #dee2e6;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            min-width: 120px;
            max-width: 120px;
            white-space: nowrap;
            font-weight: 600;
            padding: 12px 8px !important;
        }

        .actual-results-table th:first-child {
            background-color: #d1ecf1 !important;
            z-index: 15;
        }

        .actual-results-table td:first-child {
            color: var(--primary-color);
        }

        /* 优化结果表格样式 */
        .optimization-results-table {
            background-color: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .optimization-results-table .table {
            margin: 0;
            border-radius: 12px;
        }

        .optimization-results-table th {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            font-weight: 600;
            padding: 16px 20px;
            border: none;
            font-size: 1.1rem;
            text-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }

        .optimization-results-table td {
            padding: 16px 20px;
            border-bottom: 1px solid #f8f9fa;
            transition: all 0.3s ease;
            vertical-align: middle;
        }

        .optimization-results-table tbody tr {
            transition: all 0.3s ease;
        }

        .optimization-results-table tbody tr:hover {
            background-color: #f8f9fa;
            transform: translateX(3px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .optimization-results-table tbody tr:last-child td {
            border-bottom: none;
        }

        /* 参数名称样式 */
        .param-name {
            font-weight: 600;
            color: var(--primary-color);
            font-size: 1.05rem;
        }

        /* 优化值样式 */
        .optimized-value {
            font-family: "SF Mono", "JetBrains Mono", monospace;
            font-weight: 600;
            color: #28a745;
            font-size: 1.1rem;
            background: linear-gradient(135deg, #e8f5e9, #f1f8e9);
            padding: 8px 12px;
            border-radius: 6px;
            border-left: 4px solid #28a745;
        }
    </style>
</head>
<body>
    <div class="container-fluid p-0">
        <!-- 页面标题和操作按钮 -->
        <div class="page-header">
            <h1 class="page-title">敏感性分析与参数优化 - {{ project.projectname }}</h1>
            <div class="header-actions">
                <button type="button" class="btn btn-back" onclick="window.history.back()">
                    <i class="bi bi-arrow-left"></i> 返回
                </button>
            </div>
        </div>

        <!-- 标签页导航 -->
        <div class="tab-navigation">
            <button type="button" id="btnResults" class="tab-btn active">
                <i class="bi bi-graph-up-arrow"></i> 模型结果
            </button>
            <button type="button" id="btnParams" class="tab-btn">
                <i class="bi bi-sliders"></i> 参数输入
            </button>
            <button type="button" id="btnAnalysis" class="tab-btn">
                <i class="bi bi-search"></i> 敏感性分析
            </button>
            <button type="button" id="btnOptimization" class="tab-btn">
                <i class="bi bi-gear"></i> 参数优化
            </button>
        </div>

        <!-- 模型结果标签页内容 -->
        <div id="divResults" class="tab-content active">
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-graph-up-arrow"></i> 3PG模型计算结果
                    </h2>
                    <p class="parameter-subtitle">查看和对比模型计算结果的变化情况</p>
                </div>
                <div class="parameter-content">
                    <!-- 搜索框 -->
                    <div class="form-group mb-3">
                        <label for="resultSearch" class="form-label">搜索结果变量：</label>
                        <input type="text" id="resultSearch" class="form-control" placeholder="输入变量名称进行搜索...">
                    </div>

                    <!-- 结果表格容器 -->
                    <div class="results-container">
                        {% if model_results %}
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered results-table">
                                <thead class="table-success">
                                    <tr>
                                        <th>英文变量</th>
                                        <th>中文描述</th>
                                        <th>原始值</th>
                                        <th class="new-value-header">新计算值</th>
                                        <th class="change-percent-header">变化(%)</th>
                                    </tr>
                                </thead>
                                <tbody id="resultsBody">
                                    {% for result in model_results %}
                                    <tr>
                                        <td class="text-start">{{ result.english }}</td>
                                        <td class="text-start">{{ result.chinese }}</td>
                                        <td class="text-end">{{ result.value }}</td>
                                        <td class="new-value text-end">-</td>
                                        <td class="change-percent text-end">-</td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        {% else %}
                        <div class="alert alert-info text-center">
                            <i class="bi bi-info-circle"></i> 暂无模型计算结果，请先配置参数并运行计算。
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>

        <!-- 参数输入标签页内容 -->
        <div id="divParams" class="tab-content">
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-sliders"></i> 参数配置
                    </h2>
                    <p class="parameter-subtitle"></p>
                </div>
                <div class="parameter-content">
                    <!-- 参数输入容器 -->
                    <div id="inputContainer" class="mb-4">
                        {% for _ in range(1) %}
                        <div class="input-group-custom mb-3">
                            <div class="row align-items-center">
                                <div class="col-md-4">
                                    <label class="form-label">参数选择：</label>
                                    <select class="form-select param-select">
                                        {% for param in available_parameters %}
                                        <option value="{{ param.name }}" data-lb="{{ param.lower_bound }}" data-ub="{{ param.upper_bound }}">
                                            {{ param.name }} ({{ param.unit }})
                                        </option>
                                        {% endfor %}
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">原始值：</label>
                                    <input type="number" class="form-control bound-input" value="{{ available_parameters[0].lower_bound }}" readonly>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">新值：</label>
                                    <input type="number" class="form-control current-input" value="{{ available_parameters[0].lower_bound }}" step="any" min="{{ available_parameters[0].lower_bound }}" max="{{ available_parameters[0].upper_bound }}">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="button" class="btn btn-outline-danger form-control" onclick="removeRow(this)">
                                        <i class="bi bi-trash"></i> 删除
                                    </button>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div>

                    <!-- 操作按钮 -->
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-primary" onclick="addRow()">
                            <i class="bi bi-plus-circle"></i> 添加参数
                        </button>
                        <button type="button" class="btn btn-success" onclick="calculateSum()">
                            <i class="bi bi-calculator"></i> 计算结果
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 敏感性分析标签页内容 -->
        <div id="divAnalysis" class="tab-content">
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-search"></i> 敏感性分析
                    </h2>
                    <p class="parameter-subtitle">分析各参数对模型输出的影响程度，μ值越大表示参数对模型输出越敏感</p>
                </div>
                <div class="parameter-content">
                    <!-- 分析操作按钮 -->
                    <div class="d-flex gap-2 mb-4">
                        <button type="button" class="btn btn-primary" onclick="analyzeSensitivity('3pg')">
                            <i class="bi bi-play-fill"></i> 执行3PG模型敏感性分析
                        </button>
                    </div>

                    <!-- 敏感性分析结果 -->
                    <div id="threePGAnalysisResult" style="display: none;">
                        <!-- 实际结果输入区域 -->
                        <div class="card mb-4">
                            <div class="card-header bg-light">
                                <h5 class="card-title mb-0">
                                    <i class="bi bi-input-cursor"></i> 实际结果输入
                                </h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted mb-3">请输入实际观测值，用于后续的参数优化分析</p>
                                <div class="actual-results-table">
                                    <table class="table table-bordered" id="actualResultsTable">
                                        <thead class="table-info" id="actualResultsHeader"></thead>
                                        <tbody id="actualResultsBody"></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <!-- 敏感性分析结果表格 -->
                        <div class="card">
                            <div class="card-header bg-light">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="bi bi-graph-up"></i> 敏感性分析结果
                                    </h5>
                                    <input type="text" id="threePGSearch" class="form-control" style="max-width: 300px;" placeholder="搜索参数或变量...">
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="alert alert-info">
                                    <i class="bi bi-info-circle"></i>
                                    <strong>μ值说明：</strong>表示某个参数对模型输出的平均影响程度。如果μ值较大，说明该参数的变化会导致模型输出的显著变化，即该参数对模型输出高度敏感。
                                </div>
                                <div class="sensitivity-results-container">
                                    <div class="table-responsive">
                                        <table class="table table-striped table-bordered" id="threePGTable">
                                            <thead class="table-success" id="threePGHeader"></thead>
                                            <tbody id="threePGBody"></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 参数优化标签页内容 -->
        <div id="divOptimization" class="tab-content">
            <div class="parameter-section">
                <div class="parameter-header">
                    <h2 class="parameter-title">
                        <i class="bi bi-gear"></i> 参数优化
                    </h2>
                    <p class="parameter-subtitle">基于敏感性分析结果和实际观测值进行参数优化</p>
                </div>
                <div class="parameter-content">
                    <!-- 优化操作按钮 -->
                    <div class="d-flex gap-2 mb-4">
                        <button type="button" class="btn btn-success" onclick="runOptimization()" id="optimizeBtn" disabled>
                            <i class="bi bi-gear-fill"></i> 执行参数优化
                        </button>
                    </div>

                    <!-- 优化进度 -->
                    <div id="optimizationProgress" class="card mb-4" style="display: none;">
                        <div class="card-body text-center">
                            <h5><i class="bi bi-hourglass-split"></i> 正在优化中...</h5>
                            <p class="text-muted" id="estimatedTime">预计需要10-30秒...</p>
                            <div class="progress">
                                <div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated"
                                     role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>

                    <!-- 优化结果 -->
                    <div id="optimizationResult" class="card" style="display: none;">
                        <div class="card-header bg-success text-white">
                            <h5 class="card-title mb-0">
                                <i class="bi bi-check-circle"></i> 优化结果
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-success">
                                <strong>最优目标差值：</strong> <span id="optimalValue" class="fw-bold"></span>
                            </div>
                            <h6 class="mb-3">优化后的参数值：</h6>
                            <div class="optimization-results-table">
                                <table class="table">
                                    <thead>
                                        <tr>
                                            <th>参数名称</th>
                                            <th>优化后数值</th>
                                        </tr>
                                    </thead>
                                    <tbody id="optimizedParams"></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 返回顶部按钮 -->
        <div id="backToTop" class="back-to-top">
            <i class="bi bi-arrow-up"></i>
        </div>
    </div>

    <script>
        var availableParams = {{ available_parameters | tojson }};

        $(document).ready(function() {
            // 初始化页面
            initPage();

            // 处理标签页切换
            setupTabNavigation();

            // 初始化参数选择器
            initializeParameterSelectors();

            // 绑定搜索功能
            setupSearchFunctions();
        });

        // 初始化页面功能
        function initPage() {
            // 返回顶部按钮功能
            $(window).scroll(function() {
                const scrollPosition = $(window).scrollTop();
                if (scrollPosition > 300) {
                    $('#backToTop').addClass('visible');
                } else {
                    $('#backToTop').removeClass('visible');
                }
            });

            $('#backToTop').click(function() {
                $('html, body').animate({ scrollTop: 0 }, 'slow');
                return false;
            });

            // 主要计算按钮绑定
            $('#calculateBtn').click(function() {
                calculateSum();
            });
        }

        // 设置标签页导航
        function setupTabNavigation() {
            $('.tab-btn').click(function(e) {
                e.preventDefault();

                // 移除所有活跃状态
                $('.tab-btn').removeClass('active');
                $('.tab-content').removeClass('active');

                // 添加当前活跃状态
                $(this).addClass('active');

                // 获取对应的内容区域
                const targetTab = $(this).attr('id').replace('btn', 'div');
                $('#' + targetTab).addClass('active');
            });
        }

        // 初始化参数选择器
        function initializeParameterSelectors() {
            document.querySelectorAll('#inputContainer .param-select').forEach(select => {
                select.addEventListener('change', function () {
                    const param = availableParams.find(p => p.name === this.value);
                    if (param) {
                        const row = this.closest('.input-group-custom');
                        row.querySelector('.bound-input').value = param.lower_bound;
                        const currentInput = row.querySelector('.current-input');
                        currentInput.value = param.lower_bound;
                        currentInput.min = param.lower_bound;
                        currentInput.max = param.upper_bound;
                    }
                });
                select.dispatchEvent(new Event('change'));
            });
        }

        // 设置搜索功能
        function setupSearchFunctions() {
            // 结果搜索
            const resultSearch = document.getElementById('resultSearch');
            if (resultSearch) {
                resultSearch.addEventListener('input', function () {
                    const searchTerm = this.value.toLowerCase();
                    const rows = document.querySelectorAll('#resultsBody tr');
                    rows.forEach(row => {
                        const englishName = row.cells[0].textContent.toLowerCase();
                        const chineseName = row.cells[1].textContent.toLowerCase();
                        const isVisible = englishName.includes(searchTerm) || chineseName.includes(searchTerm);
                        row.style.display = isVisible ? '' : 'none';
                    });
                });
            }

            // 3PG分析结果搜索
            const threePGSearch = document.getElementById('threePGSearch');
            if (threePGSearch) {
                threePGSearch.addEventListener('input', function () {
                    const searchTerm = this.value.toLowerCase();
                    const rows = document.querySelectorAll('#threePGBody tr');
                    rows.forEach(row => {
                        const paramName = row.cells[0].textContent.toLowerCase();
                        row.style.display = paramName.includes(searchTerm) ? '' : 'none';
                    });
                });
            }
        }

        // 变量映射函数
        function getVariableMapping() {
            return {
                "林木数量 (株/ha)": "StemNo", "叶生物量 (t/ha)": "WF", "根生物量 (t/ha)": "WR", "茎生物量 (t/ha)": "WS",
                "枯落物 (t/ha)": "WL", "林分材积 (m³/ha)": "StandVol", "叶面积指数 (m²/m²)": "LAI", "平均胸径 (cm)": "avDBH",
                "灌溉量 (mm)": "Irrig", "茎生物量增量 (t/ha)": "incrWS", "死亡率 (%)": "mortality", "自疏 (株/ha)": "selfThin",
                "平均温度 (°C)": "meantemp", "肥力等级": "FR", "CO2浓度 (ppm)": "CO2", "最小可用土壤水 (mm)": "minASW",
                "林龄 (年)": "StandAge", "断面积 (m²/ha)": "BasArea", "树高 (m)": "Height", "平均年生长量 (m³/ha/年)": "MAI",
                "最大平均年生长量 (m³/ha/年)": "MAIx", "最大MAI年龄 (年)": "ageMAIx", "比叶面积 (m²/kg)": "SLA",
                "郁闭度 (%)": "CanCover", "最大LAI (m²/m²)": "LAIx", "最大LAI年龄 (年)": "ageLAIx", "总生物量 (t/ha)": "TotalW",
                "平均单株茎重 (kg)": "AvStemMass", "密度 (株/ha)": "Density", "树皮比例": "fracBB", "年龄修正因子": "fAge",
                "VPD修正因子": "fVPD", "温度修正因子": "fTemp", "CO2对量子效率影响": "fCalpha", "CO2对气孔导度影响": "fCg",
                "霜冻修正因子": "fFrost", "水分修正因子": "fSW", "养分修正因子": "fNutr", "生理修正因子": "PhysMod",
                "总初级生产力 (tC/ha)": "GPP", "净初级生产力 (tC/ha)": "NPP", "截获辐射 (MJ/m²)": "RADint",
                "冠层量子效率": "alphaC", "光能利用效率 (gDM/MJ)": "Epsilon", "冠层体积指数": "CVI", "生物量分配系数": "m",
                "分配至根的比例": "pR", "分配至茎的比例": "pS", "分配至叶的比例": "pF", "叶茎分配比": "pFS",
                "叶凋落率 (1/月)": "gammaF", "最大单株茎重 (kg)": "wSmax", "死亡率 (%/年)": "gammaN", "补充灌溉 (mm)": "supIrrig",
                "径流 (mm)": "RunOff", "雨水截留比例": "fRainInt", "雨水截留量 (mm)": "RainInt", "冠层导度 (m/s)": "CanCond",
                "水分利用效率 (gDM/kg水)": "WUE", "蒸散发 (mm)": "ET", "蒸腾 (mm)": "Transp", "可用土壤水 (mm)": "ASW",
                "日长 (h)": "DayLength", "霜冻日数 (天)": "FrostDays", "太阳辐射 (MJ/m²)": "SolarRad", "平均温度 (°C)": "Tav",
                "饱和水汽压差 (mBar)": "VPD", "降雨量 (mm)": "Rain", "长期茎生长率 (t/ha/月)": "ltStemGR", "凋落物 (t/ha)": "Litter",
                "总凋落物 (t/ha)": "TotalLitter", "茎生长效率 (tDM/ha/MJ)": "EpsilonStem", "汇集土壤水 (mm)": "pooledSW",
                "温度函数": "fT"
            };
        }

        function getVariableName(displayName) {
            const mapping = getVariableMapping();
            return mapping[displayName] || displayName;
        }

        function getDisplayName(variableName) {
            const mapping = getVariableMapping();
            for (const [display, variable] of Object.entries(mapping)) {
                if (variable === variableName) return display;
            }
            return variableName;
        }

        // 收集所有参数
        function collectAllParameters() {
            const rows = document.querySelectorAll('#inputContainer .input-group-custom');
            const modifiedValues = {};

            rows.forEach(row => {
                const select = row.querySelector('.param-select');
                const currentInput = row.querySelector('.current-input');
                const name = select.value;
                const value = parseFloat(currentInput.value);
                if (!isNaN(value)) modifiedValues[name] = value;
            });

            console.log('Collected parameters:', modifiedValues);
            return availableParams.map(param => ({
                name: param.name,
                value: (param.name in modifiedValues) ? modifiedValues[param.name] : param.lower_bound
            }));
        }

        // 更新模型结果显示
        function updateModelResults(newModelResults) {
            const resultsBody = document.getElementById('resultsBody');
            if (!resultsBody || !newModelResults) return;

            const rows = resultsBody.querySelectorAll('tr');
            rows.forEach(row => {
                const englishName = row.cells[0].textContent;
                const originalValue = parseFloat(row.cells[2].textContent);
                const newValueCell = row.querySelector('.new-value');
                const changePercentCell = row.querySelector('.change-percent');

                const newResult = newModelResults.find(result => result.english === englishName);
                if (newResult) {
                    const newValue = newResult.value;
                    newValueCell.textContent = newValue.toFixed(4);

                    if (!isNaN(originalValue) && originalValue !== 0) {
                        const changePercent = ((newValue - originalValue) / originalValue * 100).toFixed(2);
                        changePercentCell.textContent = changePercent + '%';
                        changePercentCell.className = 'change-percent text-end ' +
                            (changePercent > 0 ? 'positive-change' : changePercent < 0 ? 'negative-change' : 'no-change');
                    } else {
                        changePercentCell.textContent = '-';
                        changePercentCell.className = 'change-percent text-end';
                    }
                } else {
                    newValueCell.textContent = '-';
                    changePercentCell.textContent = '-';
                    changePercentCell.className = 'change-percent text-end';
                }
            });
        }

        // 计算结果
        function calculateSum() {
            const allParams = collectAllParameters();
            console.log('Sending parameters:', allParams);

            // 显示计算状态
            const resultsBody = document.getElementById('resultsBody');
            if (resultsBody) {
                const rows = resultsBody.querySelectorAll('tr');
                rows.forEach(row => {
                    const newValueCell = row.querySelector('.new-value');
                    const changePercentCell = row.querySelector('.change-percent');
                    if (newValueCell) newValueCell.textContent = "计算中...";
                    if (changePercentCell) changePercentCell.textContent = "";
                });
            }

            // 显示加载状态
            const calculateBtn = $('#calculateBtn');
            const originalText = calculateBtn.html();
            calculateBtn.html('<i class="bi bi-hourglass-split"></i> 计算中...');
            calculateBtn.prop('disabled', true);

            fetch('/sens/calculate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ parameters: allParams })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    showAlert('danger', `计算错误: ${data.error}`);
                    return;
                }
                if (data.model_results && resultsBody) {
                    updateModelResults(data.model_results);
                    showAlert('success', '计算完成！');

                    // 自动切换到结果标签页
                    $('#btnResults').click();
                }
            })
            .catch(error => {
                console.error('计算请求失败:', error);
                showAlert('danger', '计算请求失败，请检查网络连接或服务器状态');

                if (resultsBody) {
                    const rows = resultsBody.querySelectorAll('tr');
                    rows.forEach(row => {
                        const newValueCell = row.querySelector('.new-value');
                        const changePercentCell = row.querySelector('.change-percent');
                        if (newValueCell) newValueCell.textContent = "-";
                        if (changePercentCell) changePercentCell.textContent = "-";
                    });
                }
            })
            .finally(() => {
                // 恢复按钮状态
                calculateBtn.html(originalText);
                calculateBtn.prop('disabled', false);
            });
        }

        // 敏感性分析
        function analyzeSensitivity(type) {
            if (type !== '3pg') return;

            const params = collectAllParameters();

            // 显示加载状态
            showAlert('info', '正在执行敏感性分析，请稍候...');

            fetch('/sens/analyze_3pg', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ parameters: params })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.error || '请求失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                renderThreePGAnalysisResult(data);
                showAlert('success', '敏感性分析完成！');
            })
            .catch(error => {
                console.error("3PG分析请求失败:", error);
                showAlert('danger', `3PG模型分析失败: ${error.message}`);
            });
        }

        // 列高亮函数 - 不影响第一列
        function highlightColumn(colIndex, highlight) {
            const table = document.getElementById('threePGTable');
            const cells = table.querySelectorAll(`[data-col="${colIndex}"]:not(:first-child)`);

            cells.forEach(cell => {
                if (highlight) {
                    cell.classList.add('column-hover');
                } else {
                    cell.classList.remove('column-hover');
                }
            });
        }

        // 添加列高亮效果函数
        function addColumnHoverEffect() {
            const table = document.getElementById('threePGTable');

            // 为每个数据单元格添加鼠标事件
            table.addEventListener('mouseover', function(e) {
                if (e.target.closest('.mu-cell')) {
                    const col = e.target.closest('.mu-cell').getAttribute('data-col');
                    highlightColumn(col, true);
                }
            });

            table.addEventListener('mouseout', function(e) {
                if (e.target.closest('.mu-cell')) {
                    const col = e.target.closest('.mu-cell').getAttribute('data-col');
                    highlightColumn(col, false);
                }
            });
        }

        // 渲染3PG分析结果
        // 替换现有的 renderThreePGAnalysisResult 函数
        function renderThreePGAnalysisResult(data) {
            const thead = document.getElementById('threePGHeader');
            const tbody = document.getElementById('threePGBody');
            const actualHeader = document.getElementById('actualResultsHeader');
            const actualBody = document.getElementById('actualResultsBody');

            // 清空现有内容
            thead.innerHTML = '';
            tbody.innerHTML = '';
            actualHeader.innerHTML = '';
            actualBody.innerHTML = '';

            // 为表格添加优化类名
            const table = document.getElementById('threePGTable');
            table.classList.add('sensitivity-table');

            // 为表格容器添加优化类名
            const container = table.closest('.sensitivity-results-container');
            container.classList.add('sensitivity-table-container');

            // 构建实际结果输入表头
            let actualHeaderRow = '<tr><th class="text-start">变量</th>';
            data.output_vars.forEach(varName => {
                const displayName = getDisplayName(varName);
                actualHeaderRow += `<th class="text-center" title="${displayName}">${displayName}</th>`;
            });
            actualHeaderRow += '</tr>';
            actualHeader.innerHTML = actualHeaderRow;

            // 构建实际结果输入行
            let actualInputRow = '<tr><td class="text-start"><strong>实际值</strong></td>';
            data.output_vars.forEach((varName) => {
                actualInputRow += `<td class="text-center">
                    <input type="number" class="actual-input" data-var="${varName}" step="any" placeholder="输入实际值">
                </td>`;
            });
            actualInputRow += '</tr>';
            actualBody.innerHTML = actualInputRow;

            // 构建敏感性分析表头
            let headerRow = '<tr><th class="text-start">参数名称</th>';
            data.output_vars.forEach((varName, index) => {
                const displayName = getDisplayName(varName);
                headerRow += `<th class="text-center" data-col="${index}">${displayName}</th>`;
            });
            headerRow += '</tr>';
            thead.innerHTML = headerRow;

            // 计算μ值的范围用于颜色编码
            const allMuValues = data.mu_star.flat();
            const maxMu = Math.max(...allMuValues);
            const minMu = Math.min(...allMuValues);
            const rangeMu = maxMu - minMu;

            // 构建敏感性分析结果行
            data.names.forEach((paramName, paramIdx) => {
                const row = document.createElement('tr');
                let rowHTML = `<td class="text-start"><strong title="${paramName}">${paramName}</strong></td>`;

                data.mu_star[paramIdx].forEach((mu, varIdx) => {
                    // 根据μ值大小确定颜色等级
                    let muClass = 'mu-low';
                    if (rangeMu > 0) {
                        const normalized = (mu - minMu) / rangeMu;
                        if (normalized > 0.7) muClass = 'mu-high';
                        else if (normalized > 0.4) muClass = 'mu-medium';
                    }

                    rowHTML += `
                        <td class="mu-cell" data-col="${varIdx}">
                            <div class="mu-content">
                                <span class="mu-value ${muClass}">${mu.toFixed(3)}</span>
                                <input type="checkbox" class="optimize-checkbox form-check-input"
                                    data-param="${paramIdx}" data-var="${varIdx}">
                            </div>
                        </td>`;
                });

                row.innerHTML = rowHTML;
                tbody.appendChild(row);
            });

            // 添加列高亮效果
            addColumnHoverEffect();

            // 显示分析结果区域
            document.getElementById('threePGAnalysisResult').style.display = 'block';
            document.getElementById('optimizeBtn').disabled = false;

            // 自动切换到分析标签页
            $('#btnAnalysis').click();
        }

        // 参数优化
        function runOptimization() {
            const selected3PG = [];
            document.querySelectorAll('#threePGBody .optimize-checkbox:checked').forEach(checkbox => {
                const paramIdx = parseInt(checkbox.getAttribute('data-param'));
                const varIdx = parseInt(checkbox.getAttribute('data-var'));
                selected3PG.push({ param_idx: paramIdx, var_idx: varIdx });
            });

            if (selected3PG.length === 0) {
                showAlert('warning', '请至少选择一个参数进行优化');
                return;
            }

            const currentValues = collectAllParameters();
            const actualResults = {};

            document.querySelectorAll('#actualResultsBody .actual-input').forEach(input => {
                const varName = input.getAttribute('data-var');
                const value = parseFloat(input.value);
                if (!isNaN(value)) actualResults[varName] = value;
            });

            if (Object.keys(actualResults).length === 0) {
                showAlert('warning', '请至少输入一个实际结果值');
                return;
            }

            // 显示优化进度
            document.getElementById("optimizationProgress").style.display = "block";
            const progressBar = document.getElementById("progressBar");
            progressBar.style.width = "0%";
            progressBar.setAttribute('aria-valuenow', '0');
            document.getElementById("estimatedTime").textContent = "预计需要10-30秒...";

            // 进度条动画
            let progress = 0;
            const interval = setInterval(() => {
                if (progress < 90) {
                    progress += 5;
                    progressBar.style.width = progress + "%";
                    progressBar.setAttribute('aria-valuenow', progress);
                }
            }, 1000);

            fetch('/sens/optimize_3pg', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    selected_params: selected3PG,
                    current_values: currentValues,
                    actual_results: actualResults
                })
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(data => {
                        throw new Error(data.error || '优化请求失败');
                    });
                }
                return response.json();
            })
            .then(data => {
                clearInterval(interval);
                progressBar.style.width = "100%";
                progressBar.setAttribute('aria-valuenow', '100');
                document.getElementById("estimatedTime").textContent = `优化完成！耗时 ${data.elapsed_time} 秒`;

                setTimeout(() => {
                    document.getElementById("optimizationProgress").style.display = "none";
                }, 2000);

                // 显示优化结果
                document.getElementById('optimalValue').textContent = data.optimal_value.toFixed(6);
                const tbody = document.getElementById('optimizedParams');
                tbody.innerHTML = '';

                currentValues.forEach((param, paramIdx) => {
                    const row = document.createElement('tr');
                    const value = data.optimal_params[paramIdx][selected3PG[0].var_idx];
                    row.innerHTML = `
                        <td><span class="param-name">${param.name}</span></td>
                        <td class="text-end"><span class="optimized-value">${value !== null ? value.toFixed(6) : '-'}</span></td>
                    `;
                    tbody.appendChild(row);
                });

                document.getElementById('optimizationResult').style.display = 'block';
                showAlert('success', '参数优化完成！');

                // 自动切换到优化标签页
                $('#btnOptimization').click();
            })
            .catch(error => {
                clearInterval(interval);
                document.getElementById("optimizationProgress").style.display = "none";
                console.error("优化请求失败:", error);
                showAlert('danger', `优化失败: ${error.message}`);
            });
        }

        // 添加参数行
        function addRow() {
            const container = document.getElementById('inputContainer');
            const newRow = document.createElement('div');
            newRow.className = 'input-group-custom mb-3';

            let options = '';
            availableParams.forEach(param => {
                options += `<option value="${param.name}" data-lb="${param.lower_bound}" data-ub="${param.upper_bound}">
                    ${param.name} (${param.unit})
                </option>`;
            });

            const initialParam = availableParams[0];
            newRow.innerHTML = `
                <div class="row align-items-center">
                    <div class="col-md-4">
                        <label class="form-label">参数选择：</label>
                        <select class="form-select param-select">${options}</select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">下界值：</label>
                        <input type="number" class="form-control bound-input" value="${initialParam.lower_bound}" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">当前值：</label>
                        <input type="number" class="form-control current-input" value="${initialParam.lower_bound}" step="any" min="${initialParam.lower_bound}" max="${initialParam.upper_bound}">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <button type="button" class="btn btn-outline-danger form-control" onclick="removeRow(this)">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </div>
                </div>
            `;

            const select = newRow.querySelector('select');
            select.addEventListener('change', function () {
                const selectedParam = availableParams.find(p => p.name === this.value);
                if (selectedParam) {
                    const boundInput = this.closest('.input-group-custom').querySelector('.bound-input');
                    const currentInput = this.closest('.input-group-custom').querySelector('.current-input');
                    boundInput.value = selectedParam.lower_bound;
                    currentInput.value = selectedParam.lower_bound;
                    currentInput.min = selectedParam.lower_bound;
                    currentInput.max = selectedParam.upper_bound;
                }
            });

            container.appendChild(newRow);
        }

        // 删除参数行
        function removeRow(btn) {
            if (document.querySelectorAll('#inputContainer .input-group-custom').length > 1) {
                btn.closest('.input-group-custom').remove();
            } else {
                showAlert('warning', '至少需要保留一个参数！');
            }
        }

        // 显示提示信息
        function showAlert(type, message) {
            // 移除现有提示
            $('.floating-alert').remove();

            const alertClass = type === 'danger' ? 'alert-danger' :
                             type === 'warning' ? 'alert-warning' :
                             type === 'info' ? 'alert-info' : 'alert-success';

            const alertDiv = $(`<div class="alert ${alertClass} floating-alert fade show" role="alert">`)
                .html(`<i class="bi bi-${type === 'danger' ? 'exclamation-triangle' :
                                       type === 'warning' ? 'exclamation-circle' :
                                       type === 'info' ? 'info-circle' : 'check-circle'}"></i> ${message}`);

            $('body').append(alertDiv);

            // 自动消失
            setTimeout(() => {
                alertDiv.fadeOut(function() {
                    $(this).remove();
                });
            }, type === 'info' ? 1000 : 3000);
        }
    </script>
</body>
</html>